package com.lagou.es.controller;


import com.lagou.common.pojo.Products;
import com.lagou.es.respository.ProductRepository;
import com.lagou.es.resultmapper.ESSearchResultMapper;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/es")
public class EsController {

    @Autowired
    private ElasticsearchTemplate template;

    @GetMapping("/findByProduct")
    public List<Products> findByProduct(String name,int page,int size,double fromPrice,double toPrice) {
        // 1.架构一个原生查询器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 2.source过滤器
        queryBuilder.withSourceFilter(new FetchSourceFilter(new String[0],new String[0]));
        // 3.查询条件
        // 商品价格范围过滤
        queryBuilder.withQuery(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("name",name)).must(QueryBuilders.rangeQuery("price").from(fromPrice).to(toPrice)));

        // 4.设置分页和排序规则
        queryBuilder.withPageable(PageRequest.of((page - 1),size, Sort.by(Sort.Direction.ASC,"price")));
        // 5.高亮
        HighlightBuilder.Field field = new HighlightBuilder.Field("name");
        field.preTags("<font style='color:red>");
        field.postTags("</font>");
        queryBuilder.withHighlightFields(field);
        // 6.聚合
        // queryBuilder.addAggregation(AggregationBuilders.terms("brandAgg").field("brand"));
        // 7.查询
        AggregatedPage<Products> result = template.queryForPage(queryBuilder.build(), Products.class,new ESSearchResultMapper());
        // 获取结果
        long total = result.getTotalElements();
        // 页码
        int totalPages = result.getTotalPages();
        // 获得本页的数据集合
        List<Products> content = result.getContent();
        System.out.println(total + "  " + totalPages);
        content.stream().forEach(product -> System.out.println(product));
        return content;
    }

    @GetMapping("/createIndex")
    public void createIndex() {
        // 创建索引的方法
        template.createIndex(Products.class);
    }

    @GetMapping("/createType")
    public void createType() {
        // 创建类型映射
        template.putMapping(Products.class);
    }

}
